﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CRM_SharePoint_Transports
{
    public partial class CRMTransportConfigControl : UserControl, BlueIntegrator.Extensibility.IBlueIntegratorPropertyPage
    {
        public CRMTransportConfigControl(bool bWriteMode)
        {
            InitializeComponent();
            m_bWriteMode = bWriteMode;
            this.radioButton1.Visible = this.radioButton2.Visible = this.synchButton.Visible = this.label1.Visible = !m_bWriteMode;
            this.Text = "CRM";
        }

        bool m_bWriteMode = false;
        System.Collections.Hashtable m_data, m_origData;
        string m_portId;
        BlueIntegrator.DAL.DALBase m_dal;

        #region IBlueIntegratorPropertyPage Members

        public void Initialise(System.Collections.IDictionary data)
        {
            m_data = new System.Collections.Hashtable();
            m_origData = new System.Collections.Hashtable();

            foreach (System.Collections.DictionaryEntry dent in data)
            {
                m_data[dent.Key] = dent.Value;
                m_origData[dent.Key] = dent.Value;
            }

            BlueIntegrator.DAL.DALBase dal = data["__DAL"] as BlueIntegrator.DAL.DALBase;
            m_dal = dal;
            m_portId = data["__PortId"] as string;
            this.radioButton1.Checked = !BlueIntegrator.Helpers.Conversion.ConvertToBool(data["ReturnDelta"]);
            this.radioButton2.Checked = !this.radioButton1.Checked;
        }

        public bool ApplyChanges(System.Collections.IDictionary data)
        {
            if (data != m_data)
            foreach (System.Collections.DictionaryEntry dent in m_data)
            {
                if (dent.Value != m_origData[dent.Key] || !data.Contains(dent.Key))
                    data[dent.Key] = dent.Value;
            }

            data["ReturnDelta"] = this.radioButton2.Checked;
            return true;
        }

        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            SSISLib.CRMConfigForm scf = new SSISLib.CRMConfigForm(m_data, m_bWriteMode, m_portId, m_dal);

            if (scf.ShowDialog(this) == DialogResult.OK)
            {
            }
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            this.synchButton.Enabled = this.radioButton2.Checked;
        }

        /// <summary>
        /// Synchronize...
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void synchButton_Click(object sender, EventArgs e)
        {
            m_bCancel = false; m_bDone = false;
            m_exception = null;
            m_workerThread = new System.Threading.Thread(new System.Threading.ThreadStart(WorkerThread));
            m_workerThread.Start();

            System.Threading.Thread cancelThread = new System.Threading.Thread(new System.Threading.ThreadStart(CancelThread));
            cancelThread.Start();

            try
            {
                while (m_workerThread != null)
                {
                    System.Threading.Thread.Sleep(1000);
                    System.Windows.Forms.Application.DoEvents();
                }

                if (m_exception != null)
                    throw m_exception;
            }
            catch (System.Exception exc)
            {
                MessageBox.Show("Error : " + exc.ToString(), "BlueIntegrator", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
            finally
            {
            }
        }

        private void WorkerThread()
        {
            m_exception = null;
            m_bDone = false;

            try
            {
                System.Collections.Hashtable properties = new System.Collections.Hashtable();

                foreach (System.Collections.DictionaryEntry dent in m_data)
                {
                    properties[dent.Key] = BlueIntegrator.Messaging.SettingTokenHelper.ResolveTokens(m_dal, dent.Value);
                }

                System.Xml.XmlDocument result = SSISLib.CRMAPI.GetData(properties, null, m_dal);
                System.IO.MemoryStream memstr = new System.IO.MemoryStream();
                result.Save(memstr);
                memstr.Position = 0;
                m_dal.SaveBlobData(m_portId, memstr);
            }
            catch (System.Exception exc)
            {
                m_exception = exc;
            }

            m_bDone = true;
            m_workerThread = null;
        }

        /// <summary>
        /// Cancel dialog thread
        /// </summary>
        private void CancelThread()
        {
            SynchronizingForm sf = new SynchronizingForm();
            sf.Show();
            sf.Refresh();
            m_bCancel = false;

            while (m_workerThread != null && !m_bCancel)
            {
                sf.Update();
                m_bCancel = sf.bCancel;
                System.Windows.Forms.Application.DoEvents();
                System.Threading.Thread.Sleep(100);
            }

            if (m_bCancel && m_workerThread != null)
            {
                try
                {
                    m_workerThread.Abort();
                }
                catch
                {
                }

                m_exception = new System.OperationCanceledException();
                m_workerThread = null;
            }

            sf.Close();
            System.Windows.Forms.Application.DoEvents();
        }

        System.Threading.Thread m_workerThread = null;
        bool m_bCancel = false, m_bDone = false;
        System.Exception m_exception = null;
    }
}
